﻿using System;
using System.IO;

namespace Sencha.Serialization
{
	public sealed class JsonTextReader : JsonReaderBase
	{
		private TextReader m_reader;

		public JsonTextReader(TextReader reader)
			: this(reader, new AdHocSerializer(), DefaultBufferSize)
		{

		}
		public JsonTextReader(TextReader reader, int bufferSize = DefaultBufferSize)
			: this(reader, new AdHocSerializer(), bufferSize)
		{

		}
		public JsonTextReader(TextReader reader, ISerializationContext context, int bufferSize = DefaultBufferSize)
			: base(context, bufferSize)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");
			System.Diagnostics.Contracts.Contract.EndContractBlock();


			m_reader = reader;
		}

		protected override int FillBuffer(char[] buffer, int index)
		{
			if (buffer == null)
				throw new ArgumentNullException("buffer");
			if (index < 0 || index >= buffer.Length)
				throw new ArgumentOutOfRangeException("index");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			var count = buffer.Length - index;
			if (count <= 0)
				return index;

			var readed = m_reader.Read(buffer, index, count);
			return index + readed;
		}
	}
}
